#!/usr/local/bin/python
# -*- coding: utf-8 -*-
import sys

if(sys.getdefaultencoding()!='UTF8'):
    reload(sys)   
    sys.setdefaultencoding('UTF8')   
print sys.getdefaultencoding()
import logging
import traceback
from gameserver import GameServer
from tornado import ioloop
from tornado.escape import json_encode,json_decode
from tornado.options import define
import functools
import time
import datetime

import const
import log
import util
import user
from store import store
import process_user
import process_bar_order
from bar_order import BarOrderManager
import process_store
import process_home
import process_props
import process_other
import process_task

import process_hall_of_fame, hall_of_fame

logger = logging.getLogger(__name__)

def handle_request(request):
    '''收到请求回调'''
    cmd = ""
    content = ""
    try:
        ip = request.remote_ip
        socket_id = request.socket_id    
        cmd = request.cmd
        content = request.content      
        log.print_info(logger, "handle_request------------ IP:[%s], socked_id:[%s], cmd:[%s],content:%s" % (ip, socket_id, cmd, content))     
        
        util.onDoMethod(cmd, request, content) #命令分发
    except Exception:
        tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器    
        tmpSendMsgUtil.update_res("sys_err")  
        tmpSendMsgUtil.add_item("err_cmd", cmd) 
        tmpSendMsgUtil.add_item("err_content", content) 
        tmpSendMsgUtil.send(cmd)
        log.print_error(logger, 'handle_request error:\n%s' % traceback.format_exc())

def on_connection_closed(request):
    '''连接断开回调'''   
    try:
        socket_id = request.socket_id    
        tmpUser = user.UserManager.get_user(socket_id)
          
        if tmpUser:
            log.print_debug(logger, "on_connection_closed------------, socket_id:[%s], uid:[%s]" % (socket_id, tmpUser.getUID()))
            user.UserManager.kill_user_after_clear_info(tmpUser)  #清理用户信息

    except Exception:
        log.print_error(logger, 'on_connection_closed error:\n%s' % traceback.format_exc())

def loopCallback(): 
    '''定时回调'''
    try:
        util.TimerManager.instance().run() #调用定时器管理器
    except Exception:
        log.print_error(logger, 'loopCallback error:\n%s' % traceback.format_exc())


def startTimer(tmpType):
    '''启动定时器'''
    log.print_debug(logger, "startTimer exec, type[%s]" % tmpType)
     
    if tmpType in ["all"]:
        BarOrderManager.instance().startTimerSort()     #启动酒吧名人堂排序定时器
        BarOrderManager.instance().startTimerTList()    #启动酒吧名人堂T台队列定时器
        user.UserManager.startTimerHeartBeat()          #开启心跳定时器
        user.UserManager.startTimerLogOnline()          #开启统计在线人数定时器
        
    elif tmpType in ["timer_bar_order_sort"]:
        BarOrderManager.instance().startTimerSort()     #启动酒吧名人堂排序定时器
    elif tmpType in ["timer_t_list_push"]:
        BarOrderManager.instance().startTimerTList()    #启动酒吧名人堂T台队列定时器
    elif tmpType in ["timer_heart_beat"]:
        user.UserManager.startTimerHeartBeat()          #开启心跳定时器
    elif tmpType in ["timer_log_online"]:
        user.UserManager.startTimerLogOnline()          #开启统计在线人数定时器


def sysInitBeforeServerStart():
    '''系统资源初始化'''
    try:
        log.print_debug(logger, "++++++++sysInitBeforeServerStart exec")
        util.ConfigManager.instance().reloadConfig()            #加载配置表
        store.instance().reload()                               #加载商城列表
        startTimer("all")                                       #启动定时器
        hall_of_fame.HallOfFameManager.instance().execOrder()   #执行名人堂排序 
    except Exception:
        log.print_error(logger, '++++++++sysInitBeforeServerStart error:\n%s' % traceback.format_exc())


def main():   
    try: 
        log.configLog()

        tmpServerPort = const.Config_Port                           #绑定端口
        tmpBacklog = const.Config_Backlog                           #等待处理的最大连接数
        tmpLoopCallbackTimeMS = const.Config_LoopCallbackTimeMS     #定时回调时间(毫秒)
        log.print_debug(logger, '++++++++server start, bind port:[%s], backlog:[%s], LoopCallbackTimeMS:[%s]ms' 
                        % (tmpServerPort, tmpBacklog, tmpLoopCallbackTimeMS))        
        log.print_debug(logger, '++++++++db_host:[%s], db_name:[%s],user:[%s], pwd:[%s]' 
                        % (const.Config_Host, const.Config_DB, const.Config_User, const.Config_Pwd))
        
        sysInitBeforeServerStart()      #系统初始化 
        
        tmpExecEditDBThread = util.SqlThread()
        tmpExecEditDBThread.setDaemon(True)     #主线程结束, 子线程也结束
        tmpExecEditDBThread.start()             #---开启写DB线程
        
        tmpHallOfFameThread = hall_of_fame.HallOfFameThread()
        tmpHallOfFameThread.setDaemon(True)     #主线程结束, 子线程也结束
        tmpHallOfFameThread.start()             #---开启新版名人堂排序线程
        
        server = GameServer(handle_request,on_connection_closed)
        server.bind(port=tmpServerPort, backlog=tmpBacklog)
        server.start(1)
        
        io_loop=ioloop.IOLoop.instance()
        
        callback = functools.partial(loopCallback)
        scheduler = ioloop.PeriodicCallback(callback, tmpLoopCallbackTimeMS, io_loop=io_loop)
        
        scheduler.start()
        io_loop.start()
            
    except Exception:
        log.print_error(logger, '++++++++main error:\n%s' % traceback.format_exc())
    
    
if __name__=='__main__':
    main()

